const roleModel = require('../model/roleModel.js');
const permModel = require('../model/permModel.js')

// 角色权限数组
let rolePerms = [];

module.exports.getAllRoles = async (req, res) => {
	let result = await roleModel.getAllRole();
	res.send({
		data: result,
		meta: {
			msg: '角色管理，姓名列表获取成功',
			status: 200
		}
	})
}

/* 
返回角色  以及每个角色所对应的权限 
三级权限以树状结构返回
 */
module.exports.getAllRolesToTree = async (req, res) => {
	// 每次循环都会清空，不让数据重复出现
	 rolePerms = [];
	// 1，获取所有角色
	let roles = await roleModel.getAllRole();
	// 2，遍历所有角色
	if (roles.length > 0) {
		for (i in roles) {
			let role = roles[i];
			rolePerms.push({
				"id": role.role_id,
				"roleName": role.role_name,
				"roleDesc": role.role_desc,
				"children": []
			})
		}
	}
	// 获得所有权限
	let permes = await permModel.getAllPerm();
	// 3，遍历角色同时，同时生成角色对应的权限树
	for (i in rolePerms) {
		// 获得每个角色的权限列表
		let rperm = rolePerms[i];
		let rid = rperm.id;
		let psids = await roleModel.getPsidsByRid(rid);
		if(rid !== 0){
			 psids = psids[0].ps_ids.split(',')
			createPermTree(permes, psids, rid, i);
		}else{
			createPermTree(permes, null, rid, i);
		}
	}
	res.send({
			data: {
				rolePerm: rolePerms
			},
			meta:{
				msg:'角色列表的角色权限获取成功',
				status:200
			}
		})
}

// 生成三级菜单树
  createPermTree = (permes, psids, rid, idx)=>{
		// 生成一级菜单
		for (i in permes) {
			let perm = permes[i];
			if (perm.ps_level == 0) {
				if (rid !== 0) {
					// indexOf()返回元素在数组中的下标，如果数组中没有这个元素则返回为-1   continue跳出本次循环，进行下次循环
					if (psids.indexOf(perm.ps_id + '') < 0) continue;
				}
				rolePerms[idx].children.push({
						"id": perm.ps_id,
						"authName": perm.ps_name,
						"path": perm.ps_api_path,
						"children": []
						})
				}
			}
			// 生成二级菜单
			// 遍历每一项的一级菜单，把二级菜单对应的填进去
			for(i in rolePerms[idx].children){
				let permPar = rolePerms[idx].children[i];
				// 遍历所有的权限，把二级权限过滤出，对应的填充到一级权限里面
				for(j in permes){
					let perm = permes[j];
					// 除了过滤出二级菜单，还要把一级菜单和二级菜单对应上
					if (perm.ps_level == 1 && perm.ps_pid == permPar.id) {
						if (rid !== 0) {
							// indexOf()返回元素在数组中的下标，如果数组中没有这个元素则返回为-1   continue跳出本次循环，进行下次循环
							if (psids.indexOf(perm.ps_id + '') < 0) continue;
						}
						rolePerms[idx].children[i].children.push({
								"id": perm.ps_id,
								"authName": perm.ps_name,
								"path": perm.ps_api_path,
								"children": []
								})
						}
				}
			}
			
			// 生成三级菜单
			for(i in rolePerms[idx].children){
				for(j in rolePerms[idx].children[i].children){
					let secMenu = rolePerms[idx].children[i].children[j];
					for(id in permes){
						let perm = permes[id];
						if(perm.ps_level == 2 && perm.ps_pid == secMenu.id){
							if (rid !== 0) {
					// indexOf()返回元素在数组中的下标，如果数组中没有这个元素则返回为-1   continue跳出本次循环，进行下次循环
								if (psids.indexOf(perm.ps_id + '') < 0) continue;
							}
							rolePerms[idx].children[i].children[j].children.push({
								"id": perm.ps_id,
								"authName": perm.ps_name,
								"path": perm.ps_api_path
							})
						}
					}
				}
			}
		}
		
		// 根据id删除权限
module.exports.delPermById = async (req,res)=>{
	let {rid,pid} = req.params;
	// 1,获得角色的权限id列表
	let psids = await roleModel.getPsidsByRid(rid);
		psids = psids[0].ps_ids.split(',');  //将权限id列表转化为数组，用逗号隔开
	// 2，把要删除的权限从权限id列表中移除
	let index = psids.indexOf(pid + '')  //返回这个元素在权限id列表数组中的下标
	psids.splice(index,1);
	let psidstr = psids.toString(); //toString  将数组转化为字符串
	// 3，把角色新的权限id列表存到数据库中
	let permInfo = [psidstr,rid];
	let result = await roleModel.delOnePerm(permInfo);
	
	if(result.affectedRows > 0){
		// 生成角色新的权限菜单树
		let permes = await permModel.getAllPerm()
		let permTree = createThreeTree(rid,permes,psids);
		
		res.send({
			data:permTree,
			meta:{
				msg: '权限修改成功',
				status: 200
			}
		})
	}else{
		res.send({
			meta:{
				msg: '权限修改失败',
				status: 500
			}
		})
	}
}


// 生成三级权限菜单树
createThreeTree = (rid,permes,psids) =>{
	let permtree = [];
	for (i in permes) {
		let perm = permes[i];
		if (perm.ps_level == 0) {
			if (rid !== 0) {
				if (psids.indexOf(perm.ps_id + '') < 0) continue;
			}
			permtree.push({
					"id": perm.ps_id,
					"authName": perm.ps_name,
					"path": perm.ps_api_path,
					"children": []
			})
		}
	}
	//生成二级菜单
	//遍历每一项的一级菜单，把二级菜单对应的填进去
	for( i in permtree){
		let permPar = permtree[i];
		//遍历所有的权限，把二级权限过滤出，对应导的填充到一级权限里边
		for(j in permes) {
			let perm =  permes[j];
			//除了过滤出二级菜单，还要把一级菜单和二级菜单对应上
			if (perm.ps_level == 1 && perm.ps_pid == permPar.id ) {
				if (rid !== 0) {
					if (psids.indexOf(perm.ps_id + '') < 0) continue;
				}
				permtree[i].children.push({
						"id": perm.ps_id,
						"authName": perm.ps_name,
						"path": perm.ps_api_path,
						"children": []
				})
			}
		}
	}
	
	//生成三级菜单， 
	for(i in permtree){
		for(j in permtree[i].children){
			let secMenu = permtree[i].children[j];
			for( id in permes) {
				let perm = permes[id];
				if(perm.ps_level == 2 && perm.ps_pid == secMenu.id){
					if (rid !== 0) {
						if (psids.indexOf(perm.ps_id + '') < 0) continue;
					}
					permtree[i].children[j].children.push({
						"id": perm.ps_id,
						"authName": perm.ps_name,
						"path": perm.ps_api_path,
					})
				}
			}
		}
	}
	
	return permtree;
}


module.exports.updatePerm = async (req,res) =>{
	let {rid} = req.params;
	let {psids} = req.body;
	let permInfo = [psids,rid];
	let result = await roleModel.updataPerm(permInfo);
	if(result.affectedRows > 0) {
		res.send({
			meta: {
				msg: '权限修改成功',
				status: 200
			}
		})
	}else{
		res.send({
			meta: {
				msg: '权限修改失败',
				status: 500
			}
		})
	}
}